<template>
  <div class="com-container">
    <div class="com-chart" ref="stock_ref"></div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      chartInstance: null,
      allData: null, // 服务器返回的数据
      timeId: null, //定时器标识
      currentIndex: 0 //当前显示的页数
    };
  },
  created() {
    this.$socket.registerCallBack("stockData", this.getData)
  },
  mounted() {
    this.initChart();
    // this.getData();
    this.$socket.send({
      action: 'getData',
      socketType: 'stockData',
      chartName: 'stock',
      value: ''
    });
    window.addEventListener("resize", this.sceenAdapter);
    this.sceenAdapter();
  },
  destroyed() {
    window.removeEventListener("resize", this.sceenAdapter);
    clearInterval(this.timeId);
     this.$socket.unRegisterCallBack("stockData")
  },
  methods: {
    //初始化echartInstance对象
    async initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.stock_ref, this.theme);
      //对图表初始化配置的控制
      const initOption = {
        title: {
          text: "库存和销量分析",
          left: 20,
          top: 20,
        },

      };
      this.chartInstance.setOption(initOption);
      this.chartInstance.on("mouseover", () => {
        clearInterval(this.timeId);
      });
      this.chartInstance.on("mouseout", () => {
        this.startInterval();
      });
    },
    // 获取服务器的数据
    async getData(res) {
      // const { data: res } = await this.$http.get("stock");
      // console.log(res);
      this.allData = res;
      this.updateChart();
      this.startInterval();
    },
    // 更新图表
    updateChart() {
      //处理数据
      const centerArr = [
        ["18%", "40%"],
        ["50%", "40%"],
        ["82%", "40%"],
        ["34%", "75%"],
        ["66%", "75%"],
      ];
      const colorArr = [
        ['#4FF778', '#0BA82C'],
        ['#E5DD45', '#E8B11C'],
        ['#E8821C', '#E55445'],
        ['#5052EE', '#AB6EE5'],
        ['#23E5E5', '#2E72BF']
      ]
      const start = this.currentIndex * 5
      const end = (this.currentIndex + 1) * 5
      const showData = this.allData.slice(start, end);
      const seriesArr = showData.map((item, index) => {
        return {
          type: "pie",
          center: centerArr[index],
          hoverAnimation: false,
          labelLine: {
            show: false, //隐藏指示线
          },
          label: {
            position: "center",
            color: colorArr[index][0]
          },
          data: [
            {
              name: item.name + '\n\n' + item.sales,
              value: item.sales,
              itemStyle: {
                  color: new this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                      {
                          offset: 0,
                          color: colorArr[index][0]
                      },
                      {
                          offset: 1,
                          color: colorArr[index][1]
                      }
                  ])
              }
            },
            {
              value: item.stock,
              itemStyle: {
                  color: '#333843'
              }
            },
          ],
        };
      });
      const dataOption = {
        series: seriesArr,
      };
      this.chartInstance.setOption(dataOption);
    },
    //适应屏幕大小
    sceenAdapter() {
      const titleFontSize = (this.$refs.stock_ref.offsetWidth / 100) * 3.6;
      const innerRadius = titleFontSize * 2.8
      const outterRadius = innerRadius * 1.125
      //和分辨率相关的文字大小
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize,
          },
        },
        series: [
          {
              type: 'pie',
            radius: [outterRadius, innerRadius],
            label: {
                fontSize: titleFontSize / 2
            }
          },
          {
              type: 'pie',
            radius: [outterRadius, innerRadius],
            label: {
                fontSize: titleFontSize / 2
            }
          },
          {
              type: 'pie',
            radius: [outterRadius, innerRadius],
            label: {
                fontSize: titleFontSize / 2
            }
          },
          {
              type: 'pie',
            radius: [outterRadius, innerRadius],
            label: {
                fontSize: titleFontSize / 2
            }
          },
          {
              type: 'pie',
            radius: [outterRadius, innerRadius],
            label: {
                fontSize: titleFontSize / 2
            }
          }
        ],
      };
      this.chartInstance.setOption(adapterOption);

      this.chartInstance.resize();
    },
    startInterval() {
      if (this.timeId) {
        clearInterval(this.timeId);
      }
      this.timeId = setInterval(() => {
        this.currentIndex++
        if (this.currentIndex > 1) {
          this.currentIndex = 0
        }
        this.updateChart();
      }, 5000);
    }
  },
  computed: {
    ...mapState(['theme'])
  },
  watch: {
    theme() {
      // console.log('主题切换');
      this.chartInstance.dispose() //销毁当前的图表
      this.initChart()
      this.sceenAdapter()
      this.updateChart()

    }
  }
};
</script>
<style lang='less' scoped>
</style>